<template>
  <div class="share-dir-page">
    <div class="lately-list" v-if="!showType">
      <mobileScroll :ops="scrollOps" v-if="fileList.length!=0"  :openPullDown="true" :openUpload="false" @refreshStart="handleRS">
        <div v-for="(item,index) in fileList" :key="index" class="lately-item" @click="openItem(item)">
          <div class="lately-item-icon">
            <svg class="icon" aria-hidden="true">
              <use v-bind:xlink:href="getIcon(item.type,item.nameSuffix)"></use>
            </svg>
          </div>
          <div class="lately-item-content">
            <div class="content">
              <div class="name">{{item.name}}</div>
              <div class="time">{{item.createTime}}</div>
            </div>
          </div>
        </div>
      </mobileScroll>
      <jvs-empty imgSrc="@/assets/images/common/empty.png" v-if="fileList.length==0"></jvs-empty>
    </div>
    <div v-else class="view-file-body" :class="[formShare && 'share-view-file-body']" v-loading="fileLoading">
        <viewFileCom :formShare="formShare" :docId="enterFolderId" :tetVal="tetVal" :knowledgeInfo="knowledgeInfo" :isEpubUrl="isEpubUrl" :showType='showType' :videoSource="videoSource"  @renderFinish="renderFinish"></viewFileCom>
    </div>
  </div>
</template>

<script setup lang="ts">
import {
  ref,
  reactive,
  toRefs,
  watch ,
  onMounted,
  getCurrentInstance,
  onUnmounted
} from 'vue' 
import { getLibTree } from "@/api/knowledge";
import { useRoute } from "vue-router"
import mobileScroll from './mobileScroll.vue'
import { setSessionStore,getSessionStore,delSessionStore } from '@/utils/store.js'
import { getFileUrl } from "@/api/common";
import knowledgeInfoVue from './knowledgeInfo.vue';
import viewFileCom from './viewFileCom.vue'
import { isOffice } from '@/utils/util'
import { Base64 } from "js-base64";
const route = useRoute();

const emit = defineEmits(["renderFinish","chagneTitleName"])
const props = defineProps({
    docInfo: {
        type: Object,
        default(){
            return {}
        }
    },
    formShare:Boolean,
})
const showType = ref('')
const videoSource = ref('')
const isEpubUrl = ref('')
const tetVal = ref('')
const sessionKey = ref("")
const fileList = ref([])
const konwledgeInfo = ref({})
const enterFolderId = ref('')
const enterList = ref([])
const fileLoading = ref(false)
const knowledgeInfo = ref({})
onMounted(()=>{
    sessionKey.value = route.params.shareKey
    enterList.value = getSessionStore({name:`mobile-${sessionKey.value}`}) ||[]
    if(enterList.value.length>0){
        enterFolderId.value = enterList.value[enterList.value.length-1]
    }
    init()
})
onUnmounted(()=>{
    delSessionStore({name:`mobile-${sessionKey.value}`})
})

function init(done){
    const id = enterFolderId.value || props.docInfo.id
    getLibTree({
        id:id
    }).then(res=>{
        if(res.data.code==0){
            fileList.value = res.data.data.data
            konwledgeInfo.value = res.data.data.dcLibrary
            emit('chagneTitleName',konwledgeInfo.value.name)
            if(done) done()
        }
        emit('renderFinish')
    })
}
function renderFinish(){
    emit('renderFinish')
}
function openItem(item){
    showType.value = ''
    tetVal.value = ''
    videoSource.value = ''
    isEpubUrl.value = ''
    enterList.value.push(item.id)
    setSessionStore({name:`mobile-${sessionKey.value}`,content: enterList.value})
    enterFolderId.value = item.id
    if(item.type=="directory"){
        init()
    }else{
        knowledgeInfo.value = item
        emit('chagneTitleName',item.name)
        if(item.type=='document_upload' || isOffice(item.type)){
            if(['epub'].indexOf(item.nameSuffix)!=-1){
                showType.value = 'epub'
            }else if(['ofd'].indexOf(item.nameSuffix)!=-1){
                showType.value = 'ofd'
            }else{
                getFileUrl({id:item.id,isOnlyOffice:true,isTemplate:false}).then(res=>{
                    if(res.data.code==0){
                    if(["avi","wmv","mpg","mpeg","mov","rm","ram","swf","flv","mp4","mp3","wma","avi","rm","rmvb","flv","mpg","mkv"].indexOf(this.knowledgeInfo.nameSuffix)!=-1){
                        showType.value = 'video'
                        videoSource.value = res.data.data.url
                    }else if(['pdf'].indexOf(item.nameSuffix)!=-1){
                        let fileUrl = res.data.data.url,fileArr = res.data.data.url.split("//")
                        if(fileArr[0]!=window.location.protocol){
                        fileArr[0] = window.location.protocol
                        fileUrl = fileArr.join("//")
                        }
                        videoSource.value = fileUrl
                        showType.value = 'pdf'
                    }else if(['txt'].indexOf(item.nameSuffix)!=-1){
                        let xhr = new XMLHttpRequest();
                        xhr.open("get", res.data.data.url, true);
                        // xhr.responseType = "blob";
                        fileLoading.value = true
                        xhr.send();
                        xhr.onreadystatechange = function(){
                        if(xhr.readyState ===4 && xhr.status === 200){
                            if(isValidUTF8(xhr.responseText)){
                            self.showType = 'utf-8'
                            }else{
                            self.showType = 'error'
                            }
                            self.tetVal = xhr.responseText
                        }
                        }
                    }else{
                        showType.value='iframe'
                        let url = encodeURIComponent(Base64.encode(res.data.data.url))
                        videoSource.value = `${pluginConfig.documentUrl}/onlinePreview?url=${url}`
                    }
                    setTimeout(()=>{
                        fileLoading.value = false
                    },1000*2.5)
                    }
                })
            }
        }else{
            if(item.type=="url_address"){
                showType.value = 'iframe'
                videoSource.value = item.urlAddress
                setTimeout(()=>{
                    fileLoading.value = false
                },1000*2.5)
            }else{
                showType.value = item.type
            }
        }
    }
}
function setId(){
    showType.value = ''
    enterList.value = getSessionStore({name:`mobile-${sessionKey.value}`}) ||[]
    if(enterList.value.length>0){
        enterFolderId.value = enterList.value[enterList.value.length-1]
    }else{
        enterFolderId.value = ''
    }
    init()
}
defineExpose({
    setId
})
</script>
<style lang="scss" scoped>
.share-dir-page{
    position: relative;
    height: 100%;
    .lately-list{
      height: calc(100%);
      // overflow-y: auto;
      .lately-item{
        display: flex;
        align-items: center;
        padding: 0px 0px 0px .9375rem;
        .lately-item-icon{
          height: 4.25rem;
          display: flex;
          align-items: center;
          .icon{
            height: 1.375rem;
            width: 1.375rem;
          }
        }
        .lately-item-content{
          display: flex;
          align-items: center;
          justify-content: space-between;
          margin-left: .75rem;
          width: calc(100% - 2.125rem);
          padding-right: .9375rem;
          height: 4.25rem;
          border-bottom: .0625rem solid #eeeff0;
          .content{
            font-size: .9375rem;
            font-weight: 400;
            color: #363B4C;
            .name{
              @include SourceHanSansCN-Medium;
              margin-bottom: .25rem;
              max-width: 20.5rem;
              text-overflow: ellipsis;
              white-space: nowrap;
              overflow: hidden;
            }
            .time{
              font-size: .875rem;
              font-weight: 400;
              color: #6f7588;
              @include SourceHanSansCN-Regular;
            }
          }
        }
      }
    }
    .view-file-body{
        height: calc(100% - .25rem);
        width: 100%;
        position: relative;
        overflow: auto;
        ::v-deep(.iframe){
            height:calc(100% - 0px);
            width:100%;
            border: none;
        }
    }
}
</style>